home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3408 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.8 KB  |  72 lines

  1. Path: news.compuserve.com!newsmaster
  2. From: 73700.776@compuserve.com (Walter C. Riley)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: overiding c++ stream classes anyone?
  5. Date: Tue, 23 Jan 1996 21:37:41 GMT
  6. Organization: CompuServe Incorporated
  7. Message-ID: <4e3kh5$90r@dub-news-svc-6.compuserve.com>
  8. References: <4cqbja$62n@earth.njcc.com> <4e1d5f$5en@news02.comp.pge.com>
  9. NNTP-Posting-Host: ad45-166.compuserve.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. psk3@pge.com (Phillip Knight) wrote:
  13.  
  14. >I have pulled the last hair out of my head and still have not solved this 
  15. >problem:
  16.  
  17. >    class X : public ostream {
  18. >    public:
  19. >    ...
  20. >    X& operator<<(X& (*f)(X&)) { return (*f)(*this); }
  21. >    };
  22.  
  23.  
  24. >    X& newl(X& os) {
  25. >        cerr << "this never gets printed" << endl;
  26. >    }
  27.  
  28. >    main() {
  29. >       X foo;
  30. >       foo << "test one";
  31. >       foo << endl;
  32.  
  33. >       foo << "test two" << endl;
  34. >    }
  35.  
  36. >so the problem is simple: how do i get my manipulator newl to be called?  This 
  37. >program as stands does not compile, because inclusion of the operator '<<' 
  38. >(used in order to execute the manipulator) causes class X to no longer 
  39. >recognize the base class operators (it only recognizes X's operator <<).  
  40. >taking the operator out of the class and into the code as a function doesn't 
  41. >solve the problem either as newl never gets called.
  42.  
  43. >so anyone know a simple way of overloading a manipulator?  (all this when all
  44. >i really need is a virtual flush...)
  45.  
  46. >thanks in advance...
  47. >phil knight
  48. >psk3@pge.com
  49.  
  50. Phil,
  51. Normally, you won't overload ostream just to create a new manipulator.
  52. Try something like this:
  53.  
  54. #include <strstrea.h>
  55. #include <iomanip.h>
  56.  
  57. ostream& MyNewLine(ostream& os) {
  58.     return os << endl;
  59. }
  60.  
  61. void main() {
  62.     char buf[1000];
  63.     ostrstream os(buf, sizeof(buf));
  64.     os <<"This is a test" << MyNewLine << "to see what happens" << ends;
  65.     cout << buf;
  66. }
  67.  
  68. Good luck,
  69. Walt
  70.  
  71.  
  72.